package com.domor.service.system;

import com.domor.dao.system.MenuDao;
import com.domor.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MenuService {

    @Autowired
    private MenuDao dao;

    public Map<String, Object> getById(int id) {
        return dao.getById(id);
    }

    public List<Map<String, Object>> query(int type) {
        if(type == 1){
            return dao.query(type);
        }else {
            return getFatherMenus(dao.query(type));
        }
    }
    private List<Map<String, Object>> getFatherMenus(List<Map<String, Object>> menus) {
        List<Map<String, Object>> resultMenus = new ArrayList<>();
        for(Map<String, Object> menu : menus) {
            int id = MapUtils.getIntValue(menu, "id");
            int pid = MapUtils.getIntValue(menu, "parentId");
            if(pid == 0) {
                List<Map<String, Object>> children = getChildrenMenus(id, menus);
                // if (children != null && !children.isEmpty())
                menu.put("children", children);
                resultMenus.add(menu);
            }
        }
        return resultMenus;
    }

    private List<Map<String, Object>> getChildrenMenus(int parentId, List<Map<String, Object>> menus) {
        List<Map<String, Object>> resultMenus = new ArrayList<>();
        for(Map<String, Object> menu : menus) {
            int id = MapUtils.getIntValue(menu, "id");
            int pid = MapUtils.getIntValue(menu, "parentId");
            if(pid == 0) continue;
            if(parentId == pid) {
                List<Map<String, Object>> children = getChildrenMenus(id, menus);
                if (children != null && !children.isEmpty())
                    menu.put("children", children);
                resultMenus.add(menu);
            }
        }
        return resultMenus;
    }

    public void insert(Map<String, Object> params){
        dao.insert(params);
    }

    public void update(Map<String, Object> params){
        dao.update(params);
    }

    public void delete(Map<String, Object> params){
        dao.delete(params);
    }

}
